from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import  time
def read_html():
    browser = webdriver.Chrome()
    try:
        browser.get('https://www.baidu.com')
        input = browser.find_element_by_id('kw')
        input.send_keys('Python')
        input.send_keys(Keys.ENTER)
        #显示等待10秒，10秒内没有加载出指定控件则会抛出异常，若不指定检测的控件则此是超时时间
        wait = WebDriverWait(browser, 10)
        #设定若指定时间内未加载出id=content_left的控件则抛出异常并定位到之一啊那个，#
        #百度搜索 结果页面左侧的div容器，个容器加载完之后，等待结束
        wait.until(EC.presence_of_element_located((By.ID, 'content_left')))
        #这一行会因为页面不存在此id会抛出异常
        # print(browser.current_url)
        # print(browser.get_cookies())
        print(browser.page_source)
    finally:
        browser.close()


def get_one_element():
    browser = webdriver.Chrome()
    browser.get('https://www.taobao.com')
    input_first = browser.find_element_by_id('q')
    input_second = browser.find_element_by_css_selector('#q')
    input_third = browser.find_element_by_xpath('//*[@id="q"]')
    print(input_first, input_second, input_third)
    browser.close()


def switch_card():
    browser = webdriver.Chrome()
    browser.get('https://www.baidu.com')
    browser.execute_script('window.open()')
    print(browser.window_handles)
    browser.switch_to.window(browser.window_handles[1])
    browser.get('https://www.taobao.com')
    time.sleep(1)
    browser.switch_to.window(browser.window_handles[0])
    browser.get('https://python.org')

if __name__ == "__main__":
    switch_card()